<template>
  <div>
    <el-dialog v-model="visible" :show-close="false" destroy-on-close :close-on-click-modal="false"
      :close-on-press-escape="false">
      <template #header>
        <div>
          <span>分析变量</span>
        </div>
      </template>
      <div class="edit-body" v-loading="dialogLoding">
        <div class="left">
          <el-tree default-expand-all="true" ref="treeRef" class="filter-tree" :data="dataSource"
            @node-click="handleNodeClick" highlight-current="true" :expand-on-click-node="false">
            <template #default="{ node, data }">
              <span>{{ node.label }}</span>
              <div v-if="data.isall === 0">
                <el-button link type="success" @click="addData(data)" size="large"><el-icon class="el-input__icon">
                    <Plus />
                  </el-icon></el-button>
              </div>
              <div v-else>
                <el-button link type="danger" @click="delData(data)" size="large"><el-icon class="el-input__icon">
                    <Delete />
                  </el-icon></el-button>
              </div>
            </template>
          </el-tree>
        </div>
        <div class="right">
          <el-form :inline="true" :model="formInline" class="demo-form-inline" v-if="checked === true" label-width="80"
            formSize="default">
            <el-form-item label="名称:">
              <el-input v-model="formInline.name" size="large" disabled placeholder="设备名称" />
            </el-form-item>
            <el-form-item label="配置项:" v-if="isall == 0">
              <el-select v-model="formInline.id" class="m-2" placeholder="Select" size="large" @change="selectTopId" filterable>
                <el-option v-for="item in emitData.topOptions" :key="item.dataId" :label="item.collectitemName"
                  :value="item.dataId" />
              </el-select>
            </el-form-item>
            <template v-if="isall != 0">
              <el-form-item label="参数类型:">
                <el-select v-model="formInline.region" placeholder="参数类型" clearable size="large" style="width: 150px;">
                  <el-option label="直接设备参数" value="0" />
                  <el-option label="统计参数" value="1" />
                </el-select>
              </el-form-item>
              <!-- 直接设备参数 -->
              <template v-if="formInline.region == 0">
                <el-form-item label="直接设备:">
                  <el-select v-model="formInline.id" placeholder="请选择设备" class="m-2" size="large" @change="deviceChange" filterable style="width: 150px;">
                    <el-option-group v-for="group in emitData.deviceOption" :key="group.region" :label="group.region">
                      <el-option v-for="item in group.device" :key="item.deviceId" :label="item.name"
                        :value="item.deviceId" />
                    </el-option-group>
                  </el-select>
                </el-form-item>
              </template>

              <!-- 统计参数 -->
              <template v-if="formInline.region == 1">
                <el-form-item label="统计参数">
                  <el-select v-model="formInline.id" class="m-2" placeholder="Select" size="large"
                    @change="formulaChange">
                    <el-option v-for="item in emitData.formulaOption" :key="item.formulaId" :label="item.formulaName"
                      :value="item.formulaId" />
                  </el-select>
                </el-form-item>
              </template>
              <el-form-item label="权重:">
                <!-- <el-input
                    v-model="formInline.weight"
                    placeholder="请选择设备"
                    @change="widthChange"
                  ></el-input> -->
                <el-input-number v-model="formInline.weight" :precision="2" :step="0.1" :max="10"
                  @change="weightChange" />
              </el-form-item>
            </template>
          </el-form>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="
            visible = false;
          replaceData();
          ">取消</el-button>
          <el-button type="primary" @click="prime()"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import mitts from "@/utils/bus.js";
import { reactive, ref, onBeforeMount } from "vue";
import { save, update, del, getOne } from "@/api/formulaConfiguration";
import { isObjectValueEqual } from "@/utils/index";
import { ElMessage } from "element-plus";
const dataSource = ref([]);
const visible = ref(false);
const dialogLoding = ref(false);
const isEdit = ref(1); //1:编辑,0:新增
const isall = ref(0);
const checked = ref(false);
let index = ref(0); //数据标识
let checkIndex = ref(0); //正在编辑的数据标识
const emitData = reactive({
  //控件传入参数
  formulaOption: [],
  deviceOption: [],
  topOptions: [],
  dataId: "",
});
let formInline = reactive({
  region: "0",
  id: "",
  name: "",
  weight: "",
  label: "",
});

//接收到参数,开始处理数据
mitts.on("formulaEdit", (e) => {
  checked.value = false;
  if (e.dataId != "") {
    doDataList({ dataId: e.dataId });
    isEdit.value = 1;
  } else {
    initData();
    isEdit.value = 0;
  }
  emitData.deviceOption = e.deviceOption;
  emitData.topOptions = e.topOptions;
  emitData.formulaOption = e.formulaOption;
  visible.value = true;
});
//查询数据初始化
const doDataList = (e) => {
  getOne(e)
    .then((res) => {
      let resData = res.data;
      dataMiit(resData);
    })
    .catch((msg) => { });
};
//处理查询数据变为可用tree数据
const dataMiit = (resData) => {
  resData["label"] = resData.dataCollectConfigureName;
  resData["isall"] = 0;
  resData["id"] = resData.datacollectconfigureId;
  let templist = [];
  let upList = [];
  for (let i = 0; i < resData.argumentDeviceAddDTOList.length; i++) {
    templist.push({
      region: "0",
      id: resData.argumentDeviceAddDTOList[i].deviceId,
      name: resData.argumentDeviceAddDTOList[i].deviceName,
      weight: resData.argumentDeviceAddDTOList[i].weight,
      label: resData.argumentDeviceAddDTOList[i].deviceName,
    });
  } //设备列表
  resData.formulaConfigurationArgumentVoList; //公式列表
  for (let i = 0; i < resData.formulaConfigurationArgumentVoList.length; i++) {
    templist.push({
      region: "1",
      id: resData.formulaConfigurationArgumentVoList[i].formulaId,
      name: resData.formulaConfigurationArgumentVoList[i].formulaName,
      weight: resData.formulaConfigurationArgumentVoList[i].formulaWeight,
      label: resData.formulaConfigurationArgumentVoList[i].formulaName,
    });
  }
  resData["children"] = templist;
  upList.push(resData);
  dataSource.value = upList;
};
/**
 * tree控件添加数据
 * @param {*} data
 */
const addData = () => {
  let tempData = dataSource.value;
  tempData[0].children.push({
    label: "请选择类型",
    id: "",
    region: "0",
    name: "",
    weight: 1,
    index: index.value,
  });
  index.value += 1;
};
/**
 * tree控件删除数据
 * @param {*} data
 */
const delData = (data) => {
  getIndex(data);
  dataSource.value[0].children.splice(checkIndex.value, 1);
};
/**
 * tree控件单条数据点击事件
 * @param {*} data
 */
const handleNodeClick = (data, item) => {
  item.level == 1 ? (isall.value = 0) : (isall.value = 1);
  checked.value = true;
  //不是顶层数据
  if (isall != 0) {
    //开始处理数据
    priseData(data);
    getIndex(data);
  }
  priseData(data);
};

/**
 * 新增时初始化数据
 */
const initData = () => {
  dataSource.value = [
    {
      label: "请编辑名称",
      isall: 0,
      id: "",
      children: [],
      region: "0",
      name: "",
      weight: "",
    },
  ];
};
/**
 * 头数据更改
 * @param {*} data
 */
const selectTopId = (data) => {
  let labelname = "";
  let tempDataS = emitData.topOptions;
  for (let i = 0; i < tempDataS.length; i++) {
    if (tempDataS[i].dataId == data) {
      labelname = tempDataS[i].collectitemName;
      break;
    }
  }
  dataSource.value[0].id = data;
  dataSource.value[0].name = labelname;
  dataSource.value[0].label = labelname;
};
/**
 * 设备更改
 * @param {*} data
 */
const deviceChange = (data) => {
  let labelname = "";
  let optionList = emitData.deviceOption;
  for (let i = 0; i < optionList.length; i++) {
    for (let j = 0; j < optionList[i].device.length; j++) {
      if (optionList[i].device[j].deviceId == data) {
        labelname = optionList[i].device[j].name;
      }
    }
  }
  doCheckData({ id: data, name: labelname, region: "0" });
};
/**
 * 统计数据更改
 */
const formulaChange = (data) => {
  let labelname = "";
  let optionList = emitData.formulaOption;
  for (let i = 0; i < optionList.length; i++) {
    if (optionList[i].formulaId == data) {
      labelname = optionList[i].formulaName;
    }
  }
  doCheckData({ id: data, name: labelname, region: "1" });
};
/**
 * 权重更改
 * @param {*} data
 */
const weightChange = (data) => {
  dataSource.value[0].children[checkIndex.value].weight = data;
};

const getIndex = (data) => {
  let tempList = dataSource.value[0].children;
  for (let i = 0; i < tempList.length; i++) {
    if (isObjectValueEqual(data, tempList[i])) {
      checkIndex.value = i;
    }
  }
};
/**
 * 对正在编辑的数据进行更改
 */
const doCheckData = (updata) => {
  dataSource.value[0].children[checkIndex.value].id = updata.id;
  dataSource.value[0].children[checkIndex.value].name = updata.name;
  dataSource.value[0].children[checkIndex.value].label = updata.name;
  dataSource.value[0].children[checkIndex.value].region = updata.region;
};
/**
 * 更新form表单数据
 * @param {*} data
 */
const priseData = (data) => {
  formInline.id = data.id;
  formInline.label = data.label;
  formInline.name = data.name;
  formInline.region = data.region;
  formInline.weight = data.weight;
};

const primaryCheck = () => {
  if (dataSource.value[0].id != "") {
    let tempList = dataSource.value[0].children;
    for (let i = 0; i < tempList.length; i++) {
      if (tempList[i].id == "") {
        return false;
      }
    }
    return true;
  }
  return false;
};

/**
 * 确定按钮,进行判断是否添加还是更改
 */
const prime = () => {
  if (!primaryCheck()) {
    ElMessage.warning("请检查数据是否填写完整！");
    return;
  }
  let data = doUpdata();
  if (isEdit.value == 1) {
    update(data).then((res) => {
      if (res.status == 200) {
        ElMessage.success("更改成功！");
        mitts.emit("formulaColse", true);
        visible.value = false;
        checked.value = false;
      }
    }).catch((msg) => {

    })
    //更改
    return;
  }
  save(data)
    .then((res) => {
      if (res.status == 200) {
        ElMessage.success("新增成功！");
        mitts.emit("formulaColse", true);
        visible.value = false;
        checked.value = false;
      }
    })
    .catch((msg) => { });
};
const doUpdata = () => {
  let data = {
    datacollectconfigureId: dataSource.value[0].id,
    formulaWeight: 1,
  };
  let deviceList = [];
  let formulaList = [];
  let tempList = dataSource.value[0].children;
  for (let i = 0; i < tempList.length; i++) {
    if (tempList[i].region == "0") {
      deviceList.push({
        deviceId: tempList[i].id,
        deviceName: tempList[i].name,
        weight: tempList[i].weight, //默认：1
      });
    } else {
      formulaList.push({
        formulaId: tempList[i].id,
        formulaName: tempList[i].name,
        formulaWeight: tempList[i].weight, //默认：1
      });
    }
  }
  data["argumentDeviceAddDTOList"] = deviceList;
  data["formulaConfigurationArgumentVoList"] = formulaList;
  return data;
};


</script>

<style lang="less" scoped>
.edit-body {
  display: flex;
  justify-content: space-between;
}

.left {
  width: 35%;
  border: 1px solid;
}

.right {
  width: 57%;
  border: 1px solid;
  height: 45vh;
  text-align: center;
  padding: 20px;
}
</style>
